package com.qf.cloud2203.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyRoutingFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 注意，动态路由的filter的序号 要大于 5 (FilterConstants.PRE_DECORATION_FILTER_ORDER)
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        final RequestContext currentContext = RequestContext.getCurrentContext();

        final HttpServletRequest request = currentContext.getRequest();

        final String servicekey = request.getParameter("servicekey");

        final String method = request.getParameter("method");

        // 解析微服务的名字和接口路径
        String servcieid = getServiceId(servicekey);
        String servicePath = getServicePath(method);

        System.out.println("要转发给的微服务名称为:"+servcieid);
        System.out.println("要转发给的微服务的接口路径为:"+servicePath);

        currentContext.put(FilterConstants.SERVICE_ID_KEY,servcieid);
        currentContext.put(FilterConstants.REQUEST_URI_KEY,servicePath);

        return null;
    }

    private String getServicePath(String method) {
        return "/service2/home";
    }

    private String getServiceId(String servicekey) {
        return "SERVICE2";
    }

}
